import { defineStore } from 'pinia';

import router from '@/router';

export interface PageDataState {
  /**
   * 共享数据
   */
  sharedDataMap: Recordable<Recordable>;
}

export const usePageDataStore = defineStore({
  id: 'page-data',
  state: (): PageDataState => {
    return {
      sharedDataMap: {},
    };
  },
  getters: {
    /**
     * 当前路由fullPath
     */
    currentPageFullPath() {
      return router.currentRoute.value.fullPath;
    },
    /**
     * 当前页面共享数据
     */
    currentPageSharedData(): Recordable {
      let sharedData = this.sharedDataMap[this.currentPageFullPath];
      if (sharedData) {
        return sharedData;
      }
      sharedData = reactive<Recordable>({});
      this.sharedDataMap[this.currentPageFullPath] = sharedData;
      return sharedData;
    },
  },
  actions: {
    /**
     * 获取一个共享数据
     *
     * @param key 数据Key
     */
    get<T = any>(key: string): Undefinable<T> {
      return this.currentPageSharedData[key] as Undefinable<T>;
    },
    /**
     * 设置页面共享数据
     *
     * @param key 数据Key
     * @param data 数据
     */
    set(key: string, data: any): void {
      this.currentPageSharedData[key] = data;
    },
  },
});
